package com.wzxy.wzinfo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wzxy.util.MyTimeUtils;
import com.wzxy.wzinfo.entiry.NewsIntroduce;
import com.wzxy.wzinfo.repository.NewsIntroRepository;
import com.wzxy.wzinfo.service.INewsIntService;
import com.wzxy.wzinfo.utils.MyPage;
import com.wzxy.wzinfo.utils.QueryParamUtil;

@Service
@Transactional
public class NewsIntService extends MyJpaService<NewsIntroduce,Integer> implements INewsIntService {
	
	
	private NewsIntroRepository newsIntroRepository;

	@Autowired
	public void setNewsIntroRepository(NewsIntroRepository newsIntroRepository) {
		this.newsIntroRepository = newsIntroRepository;
		super.setJpaRepository(newsIntroRepository);
		super.setJpaSpecificationExecutor(newsIntroRepository);
	}

	@Override
	public void addNewsInt(NewsIntroduce newsIntroduce) {
		//设置状态为未审批
		newsIntroduce.setCreationTime(MyTimeUtils.getNowDateString());
		newsIntroduce.setState(0);
		newsIntroRepository.save(newsIntroduce);
	}

	/**
	 * @param loginID 不指定时为null
	 * @param startState 不指定时为null
	 * @param endState 不指定时为null 查找所有
	 */
	@Override
	public void getPage( MyPage<NewsIntroduce> myPage,Integer loginID,Integer startState, Integer endState) {
		//排序
		Sort sort = new Sort(Direction.DESC, "creationTime");
		//分页
		PageRequest pageRequest = new PageRequest(myPage.getPageNo()-1, myPage.getOnePageNum(),sort);
		
		//只查未审核和已审核 不查已删除
		NewsIntroduce n = new NewsIntroduce();
		n.setProvideId(loginID);

		//查找
		Page<NewsIntroduce> pages =  findAll(QueryParamUtil.getSpec(n,startState,endState), pageRequest);
		
		myPage.setTotal(pages.getTotalElements());
		myPage.setTotalPage(pages.getTotalPages());
		myPage.setDatas(pages.getContent());
	}

	@Override
	public void deleteNewsInt(Integer id) {
		newsIntroRepository.updataStatic(id,-1);
	}

	@Override
	public NewsIntroduce apprNews(NewsIntroduce newsIntroduce) {
		newsIntroduce.setState(1);
		newsIntroduce.setApproveTime(MyTimeUtils.getNowDateString());
		return update(newsIntroduce, newsIntroduce.getId());
	}

	@Override
	public void getLikeNewsInts(MyPage<NewsIntroduce> myPage,NewsIntroduce n,Integer startState, Integer endState) {
		//排序
				Sort sort = new Sort(Direction.DESC, "creationTime");
				//分页
				PageRequest pageRequest = new PageRequest(myPage.getPageNo()-1, myPage.getOnePageNum(),sort);
				
				//查找
				Page<NewsIntroduce> pages =  findAll(QueryParamUtil.getLikeSpec(n,startState,endState), pageRequest);
				
				myPage.setTotal(pages.getTotalElements());
				myPage.setTotalPage(pages.getTotalPages());
				myPage.setDatas(pages.getContent());
	}
}
